
#include "easylogging++.h"
#include "JsonUtil.h"
#include <iostream>
#include <fstream>
#include <sstream>
#include "Global.h"

Json::Value readJsonFile(const std::string& filename)
{
	std::ifstream ifile;
	ifile.open(filename);

	Json::CharReaderBuilder ReaderBuilder;
	ReaderBuilder["emitUTF8"] = true;

	Json::Value root;

	std::string strerr;
	bool ok = Json::parseFromStream(ReaderBuilder, ifile, &root, &strerr);
	if (!ok) {
		LOG(ERROR) << "JSON Parse Error";
	}
	return root;
}

void json2Guns(const Json::Value& JsonSetting)
{
	global_constant.uuid = JsonSetting["UUID"].asString();
	global_constant.qr_text = JsonSetting["QR_TEXT"].asBool();

	global_constant.full_magnification = JsonSetting["FULL_MAGNIFICATION"].asDouble();
	global_constant.low_magnification = JsonSetting["LOW_MAGNIFICATION"].asDouble();
	global_constant.squat_magnification = JsonSetting["SQUAT_MAGNIFICATION"].asDouble();
	global_constant.stand_magnification = JsonSetting["STAND_MAGNIFICATION"].asDouble();

	LOG(INFO) << "full_magnification: " << global_constant.full_magnification;
	LOG(INFO) << "low_magnification: " << global_constant.low_magnification;
	LOG(INFO) << "squat_magnification: " << global_constant.squat_magnification;
	LOG(INFO) << "stand_magnification: " << global_constant.stand_magnification;

	global_constant.custom = JsonSetting.get("CUSTOM", "fast").asString();

	Json::Value KeyMap = JsonSetting["KEY_MAP"];
	std::vector<std::string> KeyMapKeys = KeyMap.getMemberNames();

	for (const std::string& key : KeyMapKeys)
	{
		  std::string gunName = KeyMap[key].asString();
		  if (key == "F1")
		  {
			  global_constant.KeyGunMap[VK_F1] = gunName;
		  }
		  else if (key == "F2")
		  {
			  global_constant.KeyGunMap[VK_F2] = gunName;
		  }
		  else if (key == "F3")
		  {
			  global_constant.KeyGunMap[VK_F3] = gunName;
		  }
		  else if (key == "F4")
		  {
			  global_constant.KeyGunMap[VK_F4] = gunName;
		  }
	}

	Json::Value gunsJson = JsonSetting["GUNS"];

	// read guns
	std::vector<std::string> keys = gunsJson.getMemberNames();
	for (const auto& key : keys)
	{
		Gun gun;
		Json::Value gunJson = gunsJson[key];
		gun.name = gunJson.get("name", "").asString();
		gun.step = gunJson.get("step", 0).asInt();
		gun.magnification = gunJson.get("magnification", 1.0).asInt();
		gun.interval = gunJson.get("interval", 0).asInt();
		std::vector<int> offsetVector;
		Json::Value offsetVectorJson = gunJson["offsetVector"];
		if (offsetVectorJson.isArray())
		{
			for (const auto& item : offsetVectorJson)
			{
				offsetVector.push_back(item.asInt());
			}
		}
		gun.offsetVector = offsetVector;
		gun.computeMovements();
		LOG(DEBUG) << "============" << key << "============";
		gun.printInfo();
		global_constant.gunMap[key] = gun;
	}
}